<template>
  <ul class="ul-wrapper">
    <li @click="beforeIdx">&lt;</li>
    <li :class="{ current: currentPage == 1 }" @click="handlerCurrentPage(1)">
      1
    </li>
    <li v-show="currentPage >= 5 && totalPage > 6">&hellip;</li>
    <li
      v-for="(v, i) in middlePage"
      :key="i"
      @click="handlerCurrentPage(v)"
      :class="{ current: currentPage == v }"
    >
      {{ v }}
    </li>
    <li v-show="totalPage > 6 && currentPage < totalPage - 3">&hellip;</li>
    <li :class="{ current: currentPage == totalPage }">{{ totalPage }}</li>
    <li @click="nextIdx(currentPage + 1)">&gt;</li>
  </ul>
</template>

<script>
export default {
  props: {
    currentPage: {
      default: 1,
      type: [Number, String],
    },
    pageSize: {
      default: 5,
      type: [Number, String],
    },
    total: {
      default: 100,
      type: [Number, String],
    },
  },
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    middlePage() {
      let start = this.currentPage - 2;
      let end = this.currentPage + 2;
      if (start < 2) {
        start = 2;
      }

      if (end - start < 4) {
        end = start + 4;
      }

      if (end > this.totalPage - 1) {
        end = this.totalPage - 1;
      }

      if (end - start < 4) {
        start = end - 4;
      }

      if (start < 2) {
        start = 2;
      }

      let arr = [];
      for (let i = start; i <= end; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
  methods: {
    handlerCurrentPage(val) {
      this.$emit("handlerCurrentPage", val);
    },
    beforeIdx() {
      if (this.currentPage <= 1) return;
      this.$emit("handlerCurrentPage", this.currentPage - 1);
    },
    nextIdx() {
      if (this.currentPage >= this.totalPage) return;
      this.$emit("handlerCurrentPage", this.currentPage + 1);
    },
  },
};
</script>

<style scoped>
.ul-wrapper {
  list-style: none;
}

.ul-wrapper > li {
  float: left;
  width: 25px;
  border: 1px solid #ccc;
  font-size: 13px;
  text-align: center;
  margin-right: 5px;
  height: 20px;
  line-height: 20px;
  cursor: pointer;
}

.current {
  background-color: #409eff;
  color: #fff;
}
</style>